import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
// import 'package:url_launcher/url_launcher.dart';
import 'package:wk_robot2/app/utils/PermissionUtil.dart';
import '../../../event/MsgContentEvent.dart';
import '../../../event/WkEventListener.dart';
import '../../../routes/app_pages.dart';
import '../../../widget/CommonWidgets.dart';
class PermissionSettingController extends GetxController {


  var blueteethHasOpen = false.obs;
  var locationHashOpen = false.obs;

  Timer? _timer;

  bool jump2Connection = false;

  @override
  void onInit() {
    super.onInit();

  }

  @override
  void onReady() {
    super.onReady();

    Future.delayed(Duration(seconds: 1),() {
      PermissionUtil.requestPermission();
    });
    var _mark = false;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {

      if (GetPlatform.isAndroid) {
        if (await PermissionUtil.locationDisabled()) {
          changeLocationBtn(false);
        } else {
          changeLocationBtn(true);
        }

        if (await PermissionUtil.bluetoothDisabled()) {
          changeBlueTeethBtn(false);
        } else {
          changeBlueTeethBtn(true);
        }

      } else if (GetPlatform.isIOS) {
        BluetoothPermissionChecker checker = BluetoothPermissionChecker();

        bool isBluetoothReady = await checker.checkBluetoothStatus();
        if (isBluetoothReady) {
          changeBlueTeethBtn(true);
          print("蓝牙已开启并且权限已授权！");
        } else {
          changeBlueTeethBtn(false);
          print("蓝牙未开启或权限未授权！");

          if(_mark == false) {
            _mark = true;
            CommonWidgets.showSingleBtnDialog(Get.context!, "", "请手动打开蓝牙",
                btnText: "确定", WkEventListener(onClick: (v) {
                  // _openBluetoothSettings();
                }));
          }

        }
      }

      // if (await PermissionUtil.bluetoothDisabled()) {
      //   changeBlueTeethBtn(false);
      // } else {
      //   changeBlueTeethBtn(true);
      // }

      if (GetPlatform.isAndroid) {
        if (blueteethHasOpen.value && locationHashOpen.value && !jump2Connection) {
          bool hasPermission = await PermissionUtil.checkPermission();
          if (hasPermission) {
            jump2Connection = true;
            Get.toNamed(Routes.POWER_ONING);
          } else {
            PermissionUtil.requestPermission();
          }

        }

      } else {
        if (blueteethHasOpen.value && !jump2Connection) {
          ///bool hasPermission = await PermissionUtil.checkPermission();
          // if (hasPermission) {
          jump2Connection = true;
          Get.toNamed(Routes.POWER_ONING);
          /*} else {
            PermissionUtil.requestPermission();
          }*/

        }
      }



    });

    eventBus.on<ProductContentEvent>().listen((event) {
      if(event.code == BLUE_TEETH_ENABLE) {
        print('蓝牙可用...');
        changeBlueTeethBtn(true);

      } else if(event.code == BLUE_TEETH_UNENABLE) {
        print('蓝牙不可用...');
        changeBlueTeethBtn(false);

      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    if (_timer != null) {
      _timer!.cancel();
    }
  }


  void changeBlueTeethBtn(bool hasOpen) {
    blueteethHasOpen.value = hasOpen;
  }

  void changeLocationBtn(bool hasOpen) {
    locationHashOpen.value = hasOpen;
  }

// Future<void> _openBluetoothSettings() async {
//   const String appSettingsUrl = 'App-Prefs:root=Bluetooth'; // 示例，对于蓝牙权限，你可能需要查找正确的路径
//   final Uri url = Uri.parse(appSettingsUrl);
//
//   if (await canLaunchUrl(url)) {
//     await launchUrl(url);
//   } else {
//     throw 'Could not launch $appSettingsUrl';
//   }
// }
// MethodChannel _channel = MethodChannel('bluetooth');
// Future<void> _openBluetoothSettings() async {
//   try {
//     await _channel.invokeMethod("openBluetoothSettings");
//   } on PlatformException catch (e) {
//     print("Failed to open Bluetooth settings: '${e.message}'.");
//   }
// }

}

class BluetoothPermissionChecker {

  // 检查手机蓝牙是否开启
  Future<bool> isBluetoothEnabled() async {
    // 通过蓝牙状态流获取蓝牙的当前状态
    BluetoothAdapterState state = await FlutterBluePlus.adapterState.first;
    return state == BluetoothAdapterState.on; // 蓝牙开启状态
  }

  // 检查应用蓝牙权限
  Future<bool> checkBluetoothPermission() async {
    var status = await Permission.bluetooth.status;
    if (status.isGranted) {
      return true;
    } else {
      // 请求蓝牙权限
      var result = await Permission.bluetooth.request();
      return result.isGranted;
    }
  }

  // 检查蓝牙是否已开启且权限已获得
  Future<bool> checkBluetoothStatus() async {
    bool isBluetoothOn = await isBluetoothEnabled();
    if (!isBluetoothOn) {
      // 蓝牙未打开
      return false;
    }

    bool hasPermission = await checkBluetoothPermission();
    if (!hasPermission) {
      // 权限未授权
      return false;
    }

    return true;  // 蓝牙已打开且权限已授权
  }
}